import {
    Catch,
    ExceptionFilter,
    HttpException,
    ArgumentsHost,
    HttpStatus
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
    catch(exception: Error, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();

        const status =
            exception instanceof HttpException
                ? exception.getStatus()
                : HttpStatus.INTERNAL_SERVER_ERROR;

        const message = this.getErrorMessage(exception);

        // 确保始终返回标准JSON格式
        response.status(status).json({
            success: false,
            statusCode: status,
            path: request.url,
            message: message,
            timestamp: new Date().toISOString()
        });
    }

    private getErrorMessage(exception: Error): string {
        if (exception instanceof HttpException) {
            const response = exception.getResponse();
            return typeof response === 'object'
                ? (response as any).message || exception.message
                : exception.message;
        }
        return 'Internal server error';
    }
} 